package org.kwisatz.proxybot.core;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import org.kwisatz.proxybot.Context;
import org.kwisatz.proxybot.Filter;
import org.kwisatz.proxybot.User;

//TODO fuse with Connection
public class ContextImpl implements Context
{
	private Socket socket;
	private String nickName;
	private Map<String, Collection<User>> channels =
		new TreeMap<String, Collection<User>>();
	protected PrintWriter server;
	protected PrintWriter client;
	private RootFilter rootFilter;
	
	public String getServerHost()
	{
		return ((InetSocketAddress)socket.getRemoteSocketAddress()).getHostName();
	}
	
	public String getNickName()
	{
		return nickName;
	}

	public void setNickName(String nickName)
	{
		this.nickName = nickName;
	}

	public ContextImpl(RootFilter rootFilter, Socket s, PrintWriter server,
		PrintWriter client)
	{
		socket=s;
		this.server=server;
		this.client=client;
		this.rootFilter = rootFilter;
	}
	
	public boolean equals(Object obj)
	{
		return socket==((ContextImpl)obj).socket;
	}
		
	public int hashCode()
	{
		return socket.hashCode();
	}

	public PrintWriter getClient()
	{
		return client;
	}

	public PrintWriter getServer()
	{
		return server;
	}

	public String[] getChannels()
	{
		Set<String> s = channels.keySet();
		return s.toArray(new String[s.size()]);
	}

	public User[] getUsers(String chan)
	{
		Collection<User> l=channels.get(chan);
		return l.toArray(new User[l.size()]);
	}

	void resetChan(String string)
	{
		channels.put(string, new TreeSet<User>());
	}

	void addUser(String chan, User u)
	{
		Collection<User> l=channels.get(chan);
		if(l==null)
		{
			l=new TreeSet<User>();
			channels.put(chan, l);
		}
		l.add(u);
	}

	public void removeUser(String chan, User u)
	{
		Collection<User> l=channels.get(chan);
		if(l!=null)
		{
			l.remove(u);
		}
	}

	public Map<String, Filter> getFilters() {
		return rootFilter.getFilters();
	}
}
